package core.util;

import cache.Cache;
import cache.CacheManager;
import domain.entity.base.UserInfo;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * Created by bowen on 2017-08-14.
 */
public class ValidationUtil {

    private static final Logger logger = Logger.getLogger(ValidationUtil.class);

    public static boolean debug;
    public static String corpId;
    public static String agentId;
    public static String secret;
    public static String baidu_ak;


    static {
        try {
            ResourceBundle bundle = ResourceBundle.getBundle("validation");
            debug = Boolean.valueOf(bundle.getString("wx.config.debug"));
            corpId = bundle.getString("wx.config.corpId");
            agentId = bundle.getString("wx.config.agentId");
            secret = bundle.getString("wx.config.secret");
            baidu_ak = bundle.getString("baidu.ak");
        } catch (MissingResourceException e) {
            logger.warn("未找到validation配置文件");
        }
    }

    private static String getAccessToken() throws Exception {
        String key = "access_token";
        Cache cache = CacheManager.getCacheInfo(key);
        if (cache == null) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
            url = url.replace("APPID", corpId).replace("APPSECRET", secret);
            ClientRequest request = new ClientRequest(url);
            request.accept("application/json");
            ClientResponse<String> response = request.get(String.class);
            String responseContent = (String) response.getEntity();
            logger.info(responseContent + "++++++++++++getAccessToken+++++++");
            JSONObject json = JSONObject.fromObject(responseContent);
            cache = new Cache(key, json.get("access_token").toString(), json.getLong("expires_in"), Boolean.TRUE);
            CacheManager.putCache(key, cache);
        }
        return cache.getValue().toString();
    }


    public static String getOpenIdByCode(String code) throws Exception {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=USER_CODE&grant_type=authorization_code";
        url = url.replace("APPID", corpId).replace("APPSECRET", secret).replace("USER_CODE", code);
        ClientRequest request = new ClientRequest(url);
        request.accept("application/json");
        ClientResponse<String> response = request.get(String.class);
        String responseContent = (String) response.getEntity();
        logger.info(responseContent + "++++++++++++getOpenIdByCode+++++++");
        JSONObject json = JSONObject.fromObject(responseContent);
        String openid = "";
        if (json.get("openid") != null) {
            openid = json.get("openid").toString();
        }
        return openid;
    }

    public static UserInfo getUserInfo(String code) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        url = url.replace("ACCESS_TOKEN", getAccessToken()).replace("OPENID", getOpenIdByCode(code));
        ClientRequest request = new ClientRequest(url);
        request.accept("application/json");
        ClientResponse<String> response = request.get(String.class);
        String responseContent = (String) response.getEntity();
        logger.info(responseContent + "++++++++++++getUserInfo+++++++");
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        return objectMapper.readValue(responseContent, new TypeReference<UserInfo>() {
        });
    }


}
